package com.my.study.init.dataInit;

import cn.hutool.extra.spring.SpringUtil;
import com.my.study.utils.RedisShareUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

/**
 * 缓存数据预热实现方法
 * 实现spring的runner接口(选择其一即可)
 */
@Component
@Slf4j
public class DataInitRunner implements CommandLineRunner, ApplicationRunner {

    @Autowired
    private RedisShareUtil redisShareUtil;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("ApplicationRunner run success");
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("开始初始化数据");
        String uuid = UUID.randomUUID().toString();
        // 加锁防止多节点导致数据重复初始化
        redisShareUtil.doExecute("data_init", uuid, uuid, 200000L, uuid, (object) -> dataInit());
        log.info("数据初始化成功");
    }

    private String dataInit() {
        Map<String, DataInitService> beansOfType = SpringUtil.getBeansOfType(DataInitService.class);
        for (Map.Entry<String, DataInitService> initServiceEntry : beansOfType.entrySet()) {
            log.info("当前类:{}", initServiceEntry.getValue().getClass().getName());
            initServiceEntry.getValue().init();
        }
        return "success";
    }
}
